<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="日电量" name="day">
        <el-alert
          description="提示：数据采集截止时间为次日 08:30"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 10px"
        />
        <el-form :inline="true" :model="dayQuery" class="query-form" @submit.prevent>
          <el-form-item label="日期">
            <el-date-picker
              v-model="dayQuery.date"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="租户名称">
            <el-input
              v-model="dayQuery.qymc"
              placeholder="请输入租户名称"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="电表">
            <el-input
              v-model="selectedMeterLabel"
              placeholder="请选择电表"
              style="width: 180px"
              readonly
              @click="openMeterDialog('day')"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getDayList">查询</el-button>
            <el-button @click="resetDayQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="dayList"  style="margin-top: 10px">
          <el-table-column prop="dbbh" label="电表号" align="center" />
          <el-table-column prop="fjh" label="房间号" align="center" />
          <el-table-column prop="magnification" label="倍率" align="center" />
          <el-table-column prop="qymc" label="租户名称" align="center" width="250" show-overflow-tooltip/>
          <el-table-column prop="datetime" label="统计日期" align="center" />
          <el-table-column prop="lastReading" label="上一天读数" align="center" :formatter="formatDecimal" />
          <el-table-column prop="currentReading" label="当天读数" align="center" :formatter="formatDecimal" />
          <el-table-column prop="used" label="用电量" align="center" :formatter="formatDecimal" />
        </el-table>
        <pagination
          v-show="dayTotal > 0"
          :total="dayTotal"
          v-model:page="dayQuery.pageNum"
          v-model:limit="dayQuery.pageSize"
          @pagination="getDayList"
        />
      </el-tab-pane>
      <el-tab-pane label="日分时电量" name="hour">
        <el-form :inline="true" :model="hourQuery" class="query-form" @submit.prevent>
          <el-form-item label="日期">
            <el-date-picker
              v-model="hourQuery.date"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="电表">
            <el-input
              v-model="selectedMeterLabel"
              placeholder="请选择电表"
              style="width: 180px"
              readonly
              @click="openMeterDialog('hour')"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getHourList">查询</el-button>
            <el-button @click="resetHourQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div style="display: flex; gap: 24px;">
          <div style="flex: 1;">
            <el-card>
              <div ref="chartRef" style="height: 550px;"></div>
            </el-card>
          </div>
          <div style="width: 320px;">
            <el-table :data="hourList" border height="550" style="margin-top: 10px">
              <el-table-column prop="hour" label="小时" align="center" />
              <el-table-column prop="used" label="用电量" align="center" />
            </el-table>
            
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 电表选择弹窗 -->
    <el-dialog
      title="选择电表"
      v-model="meterDialogVisible"
      width="900px"
      append-to-body
    >
      <el-form :inline="true" :model="meterQuery" class="query-form" @submit.prevent>
        <el-form-item label="电表编号">
          <el-input v-model="meterQuery.dbbh" placeholder="请输入电表编号" style="width: 120px" />
        </el-form-item>
        <el-form-item label="智联器编号">
          <el-input v-model="meterQuery.zlid" placeholder="请输入智联器编号" style="width: 120px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getMeterList">查询</el-button>
          <el-button @click="resetMeterQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="meterTableRef"
        :data="meterDialogList"
        border
        height="500"
        
        highlight-current-row
        :row-key="row => row.dbbh"
        :current-row="selectedMeterRow"
        @current-change="handleMeterSelect"
        @selection-change="handleMeterSelectionChange"
        style="margin-bottom: 10px"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="() => true"
          :reserve-selection="false"
        />
        <el-table-column prop="qymc" label="租户名称" align="center"  width="250" show-overflow-tooltip/>
        <el-table-column prop="dbbh" label="电表编号" align="center" />
        <el-table-column prop="zlid" label="智联器编号" align="center" />
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="meterTotal > 0"
        :total="meterTotal"
        v-model:page="meterQuery.pageNum"
        v-model:limit="meterQuery.pageSize"
        @pagination="getMeterList"
      />
      <template #footer>
        <el-button @click="meterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMeterSelect">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { dayEnery, hourEnery, selectAllAmmeter } from "@/api/energy/index";
import { Search } from "@element-plus/icons-vue";
import {parseTime}from "@/utils/ruoyi"
const activeTab = ref("day");
 
/** 格式化数值为两位小数 */
function formatDecimal(row, column, cellValue) {
  if (cellValue === null || cellValue === undefined || cellValue === '') {
    return '';
  }
  return Number(cellValue).toFixed(2);
}

// 工具函数：获取昨天日期字符串
function getYesterdayStr() {
  const d = new Date();
  d.setDate(d.getDate() - 1);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

// 日电量查询
const dayQuery = reactive({
  date: getYesterdayStr(), // 默认昨天
  qymc: "",
  dbbh: "",
  pageNum: 1,
  pageSize: 10,
});
const dayList = ref([]);
const dayTotal = ref(0);

// 日分时电量查询
const hourQuery = reactive({
  date: getYesterdayStr(), // 默认昨天
  dbbh: "",
});
const hourList = ref([]); 

// 电表选择弹窗相关
const meterDialogVisible = ref(false);
const meterQuery = reactive({
  dbbh: '',
  zlid: "",
  pageNum: 1,
  pageSize: 10,
});
const meterDialogList = ref([]);
const meterTotal = ref(0);
const selectedMeterRow = ref(null);
const selectedMeterLabel = ref(""); // 展示在输入框的电表编号
let meterSelectTarget = ""; // day/hour

function openMeterDialog(target) {
  meterSelectTarget = target;
  meterDialogVisible.value = true;
  getMeterList();
}
// 获取电表列表（弹窗用，带分页）
function getMeterList() {
  selectAllAmmeter({ ...meterQuery }).then(res => {
    meterDialogList.value = res.data?.list || [];
    meterTotal.value = res.data?.total || 0;
  }).catch(() => {
    meterDialogList.value = [
    ];
    meterTotal.value = 2;
  });
}
function resetMeterQuery() {
  meterQuery.dbbh = "";
  meterQuery.zlid = "";
  meterQuery.pageNum = 1;
  meterQuery.pageSize = 10;
  getMeterList();
}
function handleMeterSelect(row) {
  selectedMeterRow.value = row;
}
function confirmMeterSelect() {
  if (!selectedMeterRow.value) return;
  selectedMeterLabel.value = selectedMeterRow.value.dbbh;
  if (meterSelectTarget === "day") {
    // dayQuery.dbbh = selectedMeterRow.value.dbbh;
    dayQuery.dbbh = selectedMeterRow.value.dbbh; // 修改为获取dbbh
  } else if (meterSelectTarget === "hour") {
    // hourQuery.dbbh = selectedMeterRow.value.dbbh;
    hourQuery.dbbh = selectedMeterRow.value.dbbh; // 修改为获取dbbh
  }
  meterDialogVisible.value = false;
}

// 只允许单选
function handleMeterSelectionChange(selection) {
  if (selection.length > 1) {
    // 只保留最后一个选中的
    const last = selection[selection.length - 1];
    selectedMeterRow.value = last;
    // 取消前面的选中
    meterDialogList.value.forEach(row => {
      if (row !== last) {
        // 通过 $refs 取消选中（需给 el-table 加 ref="meterTable"）
        if (meterTableRef.value) {
          meterTableRef.value.toggleRowSelection(row, false);
        }
      }
    });
  } else {
    selectedMeterRow.value = selection[0] || null;
  }
}

// el-table ref
const meterTableRef = ref(null);

 
// 获取日电量数据
function getDayList() {
  dayEnery({ ...dayQuery }).then(res => {
    // 正确处理日期字段
    let list = (res.data?.list || []).map(item => ({
      ...item,
      datetime: parseTime(item.date, "{y}-{m}-{d}")
    }));
    dayList.value = list;
    dayTotal.value = res.data?.total || 0;
    console.log(dayList.value, list);
  }).catch(() => {
    dayList.value = [];
    dayTotal.value = 2;
  });
}
function resetDayQuery() {
  dayQuery.date = getYesterdayStr();
  dayQuery.qymc = "";
  dayQuery.dbbh = "";
  dayQuery.pageNum = 1;
  dayQuery.pageSize = 10;
  selectedMeterLabel.value = "";
  getDayList();
}

// 获取日分时电量数据
function getHourList() {
  hourEnery({ ...hourQuery }).then(res => {
    hourList.value = res.data || []; 
    nextTick(drawChart);
  }).catch(() => {
    hourList.value = []
    console.log(hourList.value);
    nextTick(drawChart);
  });
}
function resetHourQuery() {
  hourQuery.date = "";
  hourQuery.dbbh = "";
  selectedMeterLabel.value = "";
  hourList.value = [];
  nextTick(drawChart);
}

// ECharts 折线图
const chartRef = ref();
let chartInstance = null;
function drawChart() {
  if (!chartRef.value) return;
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }
  const xData = hourList.value.map(item => item.hour);
  const yData = hourList.value.map(item => item.used);
  chartInstance.setOption({
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: xData, name: "小时" },
    yAxis: { type: "value", name: "用电量" },
    series: [
      {
        data: yData,
        type: "line",
        smooth: true,
        name: "用电量"
      }
    ]
  });
  chartInstance.resize();
}

watch(hourList, () => {
  nextTick(drawChart);
});

onMounted(() => { 
  getDayList()
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.query-form {
  margin-bottom: 10px;
}
</style>